<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 用户
 * @author www.dingwei.cn
 */
class User extends MY_Controller {
	
	/**
	 * @var DlnUserModel
	 */
	public $mUser = null;

    /**
     * @var DlnOrderModel
     */
    public $mOrder = null;

	/**
	 * @var DlnMessageModel
	 */
	public $mMessage = null;
	
	/**
	 * @var DlnFeedbackModel
	 */
	public $mFeedback = null;
	
	public function __construct(){
		parent::__construct();
	}

    /**
     * 注册发送短信验证码
     */
    public function getVerifyCode(){
        
        $this->loadModel('DlnCaptchaModel', 'mCaptcha');

        //表单验证
        $vConf = array(
            array('type', '类型', 'required|in_list[1,2,3,4,5]'),
            array('mobile', '手机号码', 'required|valid_mobile'),
            array('code', '验证码', 'required|exact_length[4]'),
            array('key', 'key', 'required'),
        );
        $this->formDataValidation($vConf);
        $type = post('type');
        $code = mt_rand(10000,99999);
        $mobile = post('mobile');
        $key = trim(post('key'));
        $code1 = trim(post('code'));
        
        $codeWhere = [
                    'key' => $key,
                    'code' => $code1,
        ];
        $this->db->select('addtime')->where($codeWhere);
        $tA = $this->mCaptcha->getOne($this->mCaptcha->tbCaptcha);
        if( ! (bool)$tA){
            $this->appReturn(0, '验证码错误');    
        }
        
        if($tA['addtime'] < time() - 60 * 10){
            $this->appReturn(0, '验证码已过期');
        }
        
        $tB = $this->mUser->mobileIsExist($mobile);
        if($type == 1 && $tB){
            $this->appReturn(0, '手机号码已注册');
        }elseif(($type == 2 || $type == 3 || $type == 5) && ! $tB){
            $this->appReturn(0, '手机号码未注册');
        }

        $tA = $this->mUser->getSmsCodeLogInfo($mobile);
        if($tA){
            $time = time() - $tA['addtime'];
            if($time < 60){
                $this->appReturn(0, '请等'.(60 - $time).'s后重新发送');
            }
        }
        $data = [
        			'code' => $code,
        			'mobile' => $mobile,
        			'addtime' => time()
        ];
        
        $query = false;
        if( ! $tA){
        	$query = $this->db->insert($this->mUser->tbVerifyCode, $data);
        }else{
        	$this->db->where('mobile', $mobile);
        	$query = $this->db->update($this->mUser->tbVerifyCode, $data);
        }

        if( ! $query){
            $this->appReturn(0, '验证码发送失败');
        }
        $msg = '您正在进行新用户注册登录操作，验证码为'.$code.'，10分钟内有效（戈壁客服绝不会索取此验证码，切勿转发或告知他人）。';
        $query = sendSms($mobile, $msg);
        if( ! $query){
            $this->appReturn(0, '验证码发送失败');
        }
        
        $this->db->where($codeWhere);
        $this->mCaptcha->delete($this->mCaptcha->tbCaptcha);
        $this->appReturn(1, '验证码已发送');
    }
    
    /**
     *验证发送手机发送的验证码是否合法
     */
    public function verifyMobileCode(){
    	//表单验证
    	$vConf = array(
    			array('mobile', '手机号码', 'required|valid_mobile'),
    			array('code', '验证码', 'required'),
    	);
    	$this->formDataValidation($vConf);
    	$mobile = trim($this->input->post('mobile'));
    	$code = trim($this->input->post('code'));
    
    	//验证验证码
    	$tA = $this->mUser->getSmsCodeLogInfo($mobile, $code);
    	
    	if( ! $tA){
    		$this->appReturn(0, '验证码错误');
    	}
    	
    	$smsExpire = time() - getCustomConfig('sms_expire') * 3600;
    	if($tA['addtime'] < $smsExpire){
    		$this->appReturn(0, '验证码过期');
    	}
    	$this->appReturn(1, '验证成功');
    }
    
    /**
     * 用户注册
     */
    public function register(){
        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
            array('code', '验证码', 'required'),
            array('password', '密码', 'required|min_length[6]|max_length[15]'),
            array('re_password', '确认密码', 'required|matches[password]'),
        );
        $this->formDataValidation($vConf);
        $mobile = trim(post('mobile'));
        $code = trim(post('code'));

        //验证手机
        $userId = $this->mUser->mobileIsExist($mobile);
        if($userId){
        	$this->appReturn(0, '手机号码已注册');
        }
        
        //验证验证码
        $tA = $this->mUser->getSmsCodeLogInfo($mobile, $code);
        if(empty($tA)) $this->appReturn(0, '验证码错误');
        $smsExpire = time() - getCustomConfig('sms_expire') * 3600;
        if($tA['addtime'] < $smsExpire){
            $this->appReturn(0, '验证码过期');
        }

        $jpushCode = uniqid().rand(1000, 9999).rand(100, 9999);

        //注册账户信息
        $data = [
        			'type' => 1,
		            'mobile' => $mobile,
		            'password' => setPassword(post('password')),
		        	'jpush_code' => $jpushCode,
        			'amount' => 0,
        			'order_type' => 0,
        			'work_status' => 1,
                    'province_id' => 0,
                    'city_id' => 0,
                    'county_id' => 0,
		            'status' => 1,
		            'addtime' => time(),
        		];

        if($this->db->insert($this->mUser->tbUser, $data)){
            $this->db->where('mobile', $mobile)
            		 ->update($this->mUser->tbVerifyCode, ['code' => '']);
            $this->appReturn(1, '注册成功');
        }
        
        $this->appReturn(0, '注册失败');
    }

	/**
	 * 用户登录
	 */
	public function login(){
		//表单验证
		$vConf = array(
					array('mobile', '手机号码', 'required|valid_mobile'),
					array('password', '密码', 'required|min_length[6]|max_length[15]'),
				);

		$this->formDataValidation($vConf);
		$mobile = trim(post('mobile'));
		$password = setPassword(post('password'));
		$tA = $this->mUser->getInfoByMobileAndPassword($mobile, $password);
		if(empty($tA)){
			$this->appReturn(0, '用户不存在或密码错误');
		}
		if($tA['status'] == 4){
			$this->appReturn(0, '账户已停用');	
		}
		
		//设置sessid
		$key = config_item('encryption_key');
		$sessionId = encryption($tA['id'].$key.time().mt_rand(10,100000));
		
		$data = [
				'deliveryman_id' => $tA['id'],
				'sessionid' => $sessionId,
				'type' => 1,
				'addtime' => time()
		];
		$this->db->where('deliveryman_id', $tA['id'])
				 ->where('type', 1);
		$tI = $this->mUser->count($this->mUser->tbSession);
		$query = false;
		if($tI){
			$query = $this->db->where('deliveryman_id', $tA['id'])
							 ->where('type', 1)
							 ->update($this->mUser->tbSession, ['sessionid' => $sessionId]);
		}else{
			$query = $this->db->insert($this->mUser->tbSession, $data);		
		}
		if($query){
			$data = array(
                		'sessionid' => encode($sessionId),
						'jpush_code' => $tA['jpush_code'],
						'work_status' => $tA['work_status'],
			            'status' => $tA['status']
			);			
			$this->appReturn(1, '已登录', $data);		
		}
		
		$this->appReturn(0, '登录失败');
	}
	
	/**
	 * 忘记密码
	 */
	public function forgetPassword(){
		//表单验证
		$vConf = array(
					array('mobile', '手机号码', 'required|valid_mobile'),
					array('code', '验证码', 'required'),
					array('password', '密码', 'required|min_length[6]|max_length[15]'),
					array('re_password', '确认密码', 'required|matches[password]'),
				);
		$this->formDataValidation($vConf);	
		$mobile = trim(post('mobile'));
		$code = trim(post('code'));

		//验证验证码
		$tA = $this->mUser->getSmsCodeLogInfo($mobile, $code);	
		if(empty($tA)) $this->appReturn(0, '验证码错误');
		$smsExpire = time() - getCustomConfig('sms_expire') * 3600;
		if($tA['addtime'] < $smsExpire){
			$this->appReturn(0, '验证码过期');				
		}
		
		//验证手机
		$userId = $this->mUser->mobileIsExist($mobile);
		if( ! $userId){
			$this->appReturn(0, '手机号码未注册');
		}
		
		$this->db->where('mobile', $mobile);
		if($this->db->update($this->mUser->tbUser, ['password' => setPassword(post('password'))])){
			$this->db->where('mobile', $mobile)
					 ->update($this->mUser->tbVerifyCode, ['code' => '']);
			$this->appReturn(1, '密码已更改，请登录');
		}
		
		$this->appReturn(0, '密码更改失败');
	}

    /**
     * 修改密码
     */
    public function password(){

        //表单验证
        $vConf = array(
            array('old_password', '旧密码', 'required|min_length[6]|max_length[15]'),
            array('password', '新密码', 'required|min_length[6]|max_length[15]'),
            array('re_password', '确认密码', 'required|matches[password]'),
        );
        $this->formDataValidation($vConf);
        $mobile = $this->userMobile;
        $oldPassword = setPassword(post('old_password'));
        //验证手机
        $userId = $this->mUser->getInfoByMobileAndPassword($mobile, $oldPassword);
        if(empty($userId)){
            $this->appReturn(0, '旧密码错误');
        }

        $data = [
        			'password' => setPassword(post('password'))
        		];
        $this->db->where('id', $this->userId);
        if($this->db->update($this->mUser->tbUser, $data)){
        	$this->db->where('deliveryman_id', $this->userId)
        			 ->update($this->mUser->tbSession, ['sessionid' => '']);
            $this->appReturn(1, '密码已更改，请重新登录');
        }
        $this->appReturn(0, '修改失败');
    }
    
    /**
     * 更换手机号码
     */
    public function changeMobile(){
    	
    	//表单验证
    	$vConf = array(
    			array('mobile', '新手机号码', 'required|valid_mobile'),
    			array('code', '新手机验证码', 'required'),
    			array('old_code', '旧手机验证码', 'required'),
    	);
    	
    	$tA = $this->mUser->getSmsCodeLogInfo($this->userMobile, trim(post('old_code')));
    	if(empty($tA)){
    		$this->appReturn(0, '更换失败');
    	}
    	
    	$mobile = trim(post('mobile'));
    	$tI = $this->mUser->mobileIsExist($mobile);
    	if($tI){
    		$this->appReturn(0, '更换失败，手机号码已注册');
    	}
    	
    	$tA = $this->mUser->getSmsCodeLogInfo($mobile, trim(post('code')));
    	if(empty($tA)){
    		$this->appReturn(0, '验证码错误');
    	}
    	$smsExpire = time() - getCustomConfig('sms_expire') * 3600;
    	if($tA['addtime'] < $smsExpire){
    		$this->appReturn(0, '验证码过期');
    	}
    	
    	$tB = $this->db->where('id', $this->userId)
    	         ->update($this->mUser->tbUser, ['mobile' => $mobile]);
    	if( ! $tB){
    		$this->appReturn(0, '更换失败');
    	}
    	
    	$this->db->where('deliveryman_id', $this->userId)
    			 ->where('type', 1)
    			 ->update($this->mUser->tbSession, ['sessionid' => '']);
    	
    	$this->db->where_in('mobile', [$this->userMobile, $mobile])
    			 ->update($this->mUser->tbVerifyCode, ['code' => '']);
    	$this->appReturn(1, '更换成功，请重新登录');
    }
    
    /**
     * 设置支付密码
     */
    public function setPayPasswd(){
    	
    	//表单验证
    	$vConf = array(
    			array('code', '短信验证码', 'required'),
    			array('password', '支付密码', 'required|exact_length[6]'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$code = trim(post('code'));
    	$password = setPassword(post('password'));
    	
    	$tCode = $this->mUser->getSmsCodeLogInfo($this->userMobile, $code);
    	if(! $tCode){
    		$this->appReturn(0, '验证码错误');
    	}
    	$smsExpire = time() - getCustomConfig('sms_expire') * 3600;
    	if($tCode['addtime'] < $smsExpire){
    		$this->appReturn(0, '验证码过期');
    	}
    	
    	$query = $this->db->where('id', $this->userId)
    					  ->update($this->mUser->tbUser, ['pay_password' => $password]);
    	if ( ! $query){
    		$this->appReturn(0,'支付密码设置失败');
    	}
    	
    	$this->db->where('mobile', $this->userMobile)
    			->update($this->mUser->tbVerifyCode, ['code' => '']);
    	$this->appReturn(1,'支付密码设置成功');
    }
    
    /**
     * 认证
     */
    public function auth(){
    	
    	$this->loadModel('AdmSettingModel', 'mSett', 'admin');
    	
    	//表单验证
    	$vConf = array(
    			array('name', '姓名', 'required|max_length[6]|valid_chinese'),
    			array('identity_card', '身份证', 'required|valid_idcard'),
    			array('province_id', '省份', 'required|is_natural_no_zero'),
    			array('city_id', '城市', 'required|is_natural_no_zero'),
    			array('county_id', '区县', 'required|is_natural_no_zero'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$provinceId = post('province_id');
    	$cityId = post('city_id');
    	$countyId = post('county_id');
    	
    	$tA = $this->mSett->getLocationNameByIds([$provinceId, $cityId, $countyId]);
    	if(count($tA) != 3){
    	    $this->appReturn(0, '区域错误');
    	}
    	
    	$data = [
    				'name' => trim(post('name')),
    	            'province_id' => $provinceId,
            	    'city_id' => $cityId,
            	    'county_id' => $countyId,
    				'identity_card' => trim(post('identity_card')),
    				'status' => 5
    		];
    	if($this->userStatus == 5){
    		$this->appReturn(0, '您的认证资料已提交，不能重复提交');
    	}elseif($this->userStatus == 2){
    		$this->appReturn(0, '已通过认证，不能再编辑');
    	}
    	
    	if( ! isset($_FILES['portrait'])){
    		$this->appReturn(0, '必须上传头像');	
    	}
    	
    	if( ! isset($_FILES['identity_card_img'])){
    		$this->appReturn(0, '必须上传身份证照片');	
    	}
    	
    	$tA = $this->mSett->getLocationNameByIds([$provinceId, $cityId, $countyId]);
    	if(count($tA) != 3){
    		$this->appReturn(0, '区域错误');
    	}
    	
    	$path = 'uploads/'.$this->port.'/'.$this->userId;
    	$tA = imageUpload($path, 'portrait', 'portrait', true, 300, 300, 
    			['min_width' => '400', 'min_height' => 400]);
    	if( ! $tA['status']){
    		$this->appReturn(0, '头像上传失败');
    	}
    	$data['portrait'] = $tA['data'];
    	
    	$path = 'uploads/'.$this->port.'/'.$this->userId;
    	$tA = imageUpload($path, 'identity_card_img', 'identity_card', true, 300, 300, 
    			['min_width' => '400', 'min_height' => 400]);
    	if( ! $tA['status']){
    		$this->appReturn(0, $tA['data']);
    	}
    	$data['identity_card_img'] = $tA['data'];
    	$query = $this->db->where('id', $this->userId)
    			 		  ->update($this->mUser->tbUser, $data);
    	if( ! $query){
    		$this->appReturn(0, '认证资料提交失败');
    	}
    	
    	$this->appReturn(1, '认证资料提交成功，请等待后台审核');
    }
    
    /**
     * 设置接单类型
     */
    public function orderType(){
        
        $this->loadModel('DlnOrderModel', 'mOrder', 'deliveryman');
        $typeConfig = array_keys($this->mOrder->type());
        $type = post('type');
        if(is_array($type)){
            $this->appReturn(0, '参数错误');
        }
        
        $tA = explode(',', $type);
        foreach ($tA as $v){
            if( ! in_array($v, $typeConfig)){
                $this->appReturn(0, '参数错误');
            }
        }
    	
        $data = ['order_type' => $type];
    	$query = $this->db->where('id', $this->userId)
    			 		  ->update($this->mUser->tbUser, $data);
    	if( ! $query){
    		$this->appReturn(0, '保存失败');
    	}
    	
    	$this->appReturn(1, '保存成功');
    }
    
    /**
     * 设置是否是工作状态
     */
    public function workStatus(){
        
        //表单验证
        $vConf = array(
            array('status', '工作状态', 'required|in_list[1,2]'),
        );
        $this->formDataValidation($vConf);
        
        $data = ['work_status' => post('status')];
        $query = $this->db->where('id', $this->userId)
        ->update($this->mUser->tbUser, $data);
        if( ! $query){
            $this->appReturn(0, '保存失败');
        }
        
        $this->appReturn(1, '保存成功');
    }
    
    /**
     * 获取用户详细信息
     */
    public function getInfo(){
        
        $this->loadModel('DlnMessageModel', 'mMessage');
        $this->loadModel('AdmSettingModel', 'mSett', 'admin');
        $this->loadModel('DlnOrderModel', 'mOrder');
    	$tA = $this->mUser->getInfo($this->userId);

    	$tB = $this->mMessage->hasNewMessage($this->userId);
    	$sett = $this->mSett->get('postion_time,customer_tel,income_description', 'deliveryman');
    	$data = [
    	           'name' => $tA['name'],
    	           'portrait' => $tA['status'] == 2?$tA['portrait']:'',
    	           'mobile' => $tA['mobile'],
    	           'province_id' => $tA['province_id'],
    	           'city_id' => $tA['city_id'],
    	           'county_id' => $tA['county_id'],
    	           'province' => $tA['province'],
    	           'city' => $tA['city'],
    	           'county' => $tA['county'],
    	           'identity_card' => $tA['identity_card'],
    	           'identity_card_img' => $tA['identity_card_img'],
    	           'status' => $tA['status'],
    	           'score' => $tA['score'],
    	           'order_type' => $tA['order_type'],
    	           'work_status' => $tA['work_status'],
    	           'amount' => $tA['amount'],
    	           'pay_password' => $tA['pay_password'],
    	           'has_new_message' => $tB ? 2 : 1,
    	           'postion_time' => $sett['postion_time'],
    	           'customer_tel' => $sett['customer_tel'],
    	           'income_description' => $sett['income_description'],
    	           'complete_order' => $this->mOrder->getTodayCountBuyDeliverymanId($this->userId, 4)
    	];

    	$data['remarks'] = $this->mUser->getNewOneAuthRemarks($this->userId);
    	unset($data['id'], $data['type']);
    	$this->appReturn(1, '', $data);
    }
    
    /**
     * 定位
     */
    public function postion(){
    	
        //表单验证
        $vConf = array(
            array('longitude', '纬度', 'required|is_numeric'),
            array('latitude', '经度', 'required|is_numeric'),
        );
        $this->formDataValidation($vConf);
        
        $data = [
            'longitude' => post('longitude'),
            'latitude' => post('latitude')
        ];
        
        $this->db->where('id', $this->userId);
        if($this->mUser->update($this->mUser->tbUser, $data)){
            $this->appReturn(1, '');
        }
        $this->appReturn(0);
    }
    
    /**
     * 添加银行卡
     */
    public function saveBankCard(){
    	
    	//表单验证
    	$vConf = array(
    			array('bank_id', '银行', 'required'),
    			array('code', '卡号', 'required|valid_bankcardcode'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$bankId = trim(post('bank_id'));
    	$code = trim(post('code'));
    	$id = post('id');
    	
    	if($id){
	    	$this->db->where(['id' => $id, 'deliveryman_id' => $this->userId]);
	    	$tI = $this->mUser->count($this->mUser->tbBankCard);
	    	if( ! $tI){
	    		$this->appReturn(0, '编辑的银行卡不存在');
	    	}
    	}
    	
    	$this->db->where(['deliveryman_id' => $this->userId, 'code' => $code]);
    	if($id) $this->db->where('id <>', $id);
    	$tI = $this->mUser->count($this->mUser->tbBankCard);
    	if($tI){
    		$this->appReturn(0, '卡号已经添加，不能重复添加一样的卡号');
    	}
    	
    	$this->db->where(['deliveryman_id' => $this->userId]);
    	$tI = $this->mUser->count($this->mUser->tbBankCard);
    	if($tI > 10){
    		$this->appReturn(0, '最多只能添加10张银行卡');
    	}
    	
    	$this->loadModel('AdmSettingModel', 'mSett', 'admin');
    	if( ! $this->mSett->existBank($bankId)){
    		$this->appReturn(0, '银行不存在');
    	}
    	
    	$data = [
    				'deliveryman_id' => $this->userId,
    				'bank_id' => $bankId,
    				'code' => $code
    		];
    	
    	$query = false;
    	if($id){
    		$this->db->where(['id' => $id, 'deliveryman_id' => $this->userId]);
    		$query = $this->mUser->update($this->mUser->tbBankCard, $data);
    	}else{
    		$data['addtime'] = time();
    		$query = $this->mUser->insert($this->mUser->tbBankCard, $data);
    	}
    	
    	if( ! $query){
    		$this->appReturn(0, '保存失败');
    	}
    	
    	$this->appReturn(1, '保存成功');
    }
    
    /**
     * 获取银行卡列表
     */
    public function getBankCardList(){
    	
    	$this->loadModel('AdmSettingModel', 'mSett', 'admin');
    	$this->db->select('id,bank_id,code')
    	          ->where('deliveryman_id', $this->userId)
    	          ->order_by('addtime desc');
    	$data = $this->mUser->getAll($this->mUser->tbBankCard);
    	$bankId = [];
    	foreach ($data as $v){
    		$bankId[] = $v['bank_id'];
    	}
    	$tA = [];
    	if($bankId){
    	   $tA = $this->mSett->getBankByIds($bankId);
    	}
    	foreach ($data as $k => $v){
    		$data[$k]['bank_name'] = isset($tA[$v['bank_id']]) ? $tA[$v['bank_id']]['name'] : '';
    		$data[$k]['icon'] = isset($tA[$v['bank_id']]) ? $tA[$v['bank_id']]['icon'] : '';
    	}
    	
    	$this->appReturn(1, '', $data);
    }
    
    /**
     * 删除银行卡
     */
    public function deleteBankCard(){
    	
    	$id = post('id');
    	$this->db->where(['id' => $id, 'deliveryman_id' => $this->userId]);
    	if($this->mUser->delete($this->mUser->tbBankCard)){
    		$this->appReturn(1, '已删除');
    	}
    	
    	$this->appReturn(0, '删除失败');
    }
    
    /**
     * 资金提现
     */
    public function withdrawCash(){
    	
    	$this->loadModel('AdmSettingModel', 'mSett', 'admin');
    	//表单验证
    	$vConf = array(
    				array('amount', '金额', 'required|numeric'),
    				array('card_id', '银行卡', 'required|is_natural_no_zero'),
    	            array('password', '支付密码', 'required|exact_length[6]')
    	);
    	$this->formDataValidation($vConf);
    	$amount = post('amount');
    	$cardId = post('card_id');
    	
    	$this->_verifyPayPassword(post('password'));
    	
    	$tI = $this->mSett->get('min_withdraw_cash_amount', 'deliveryman');
    	if($amount < $tI){
    		$this->appReturn(0, '提现金额必须大于等于：'.$tI);
    	}
    	
    	$userAmount = $this->mUser->getAmount($this->userId);
    	if($userAmount < $amount){
    		$this->appReturn(0, '余额不足，最多只能提现'.$userAmount.'元');
    	}
    	
    	$this->db->select('bank_id,code')
    			 ->where('deliveryman_id', $this->userId)
    			 ->where('id', $cardId);
    	$bank = $this->mUser->getOne($this->mUser->tbBankCard);
    	if( ! $bank){
    		$this->appReturn(0, '银行卡不存在');	
    	}
    	
    	$tA = $this->mSett->getBankByIds([$bank['bank_id']]);
    	if( ! $tA){
    		$this->appReturn(0, '银行卡错误');
    	}
    	
    	$data = [
    				'deliveryman_id' => $this->userId,
    				'order_id' => 0,
    				'amount' => -$amount,
    				'type' => 2,
    				'status' => 1,
    	            'bank' => json_encode(['code' => $bank['code'], 'bank' => $tA[$bank['bank_id']]['name']]),
    				'addtime' => time()
    		];
    	$this->db->trans_begin();
    	$query = $this->mUser->insert($this->mUser->tbAmountDetails, $data);
    	if( ! $query){
    		$this->db->trans_rollback();
	    	$this->appReturn(0, '申请提交失败');		
    	}
    	
    	$data = ['amount' => $userAmount - $amount];
    	$this->db->where('id', $this->userId);
    	if( ! $this->mUser->update($this->mUser->tbUser, $data)){
    		$this->db->trans_rollback();
    		$this->appReturn(0, '申请提交失败');
    	}
    	
    	$this->db->trans_commit();
    	$this->appReturn(1, '申请已提交');		
    }
    
    /**
     * 获取余额详情
     */
    public function getAmountDetails(){
    	
    	//表单验证
    	$vConf = array(
    			array('page', '页码', 'required|numeric'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$date = post('date');
    	if($date){
    		$star = strtotime($date);
    		$end = strtotime('+1day', $star);
    		$this->db->where('addtime >=', $star)
    				 ->where('addtime <', $end);
    	}
    	
    	$this->db->select('id,amount,type,status,addtime')
                 ->where('deliveryman_id', $this->userId)
    			 ->order_by('id desc');
    	$data = $this->mUser->appPage($this->mUser->tbAmountDetails, post('page'));
    	$list = [];
    	foreach ($data['list'] as $k => $v){
    		$list[$k] = [
    						'id' => $v['id'],
    						'type' => $v['type'],
    						'type_show' => $this->mUser->amountDetailsType($v['type'])
    				.'（'.$this->mUser->amountDetailsStatus($v['status']).'）',
    						'amount' => $v['amount'],
    						'addtime' => date('Y-m-d H:i:s', $v['addtime'])
    		];
    	}
    	
    	$data['list'] = $list;
    	$this->appReturn(1, '', $list);
    }
    
    /**
     * 获取消息列表
     */
    public function getMessageList(){
    	
    	$this->loadModel('DlnMessageModel', 'mMessage');
    	//表单验证
    	$vConf = array(
    			array('page', '页码', 'required|numeric'),
    			array('type', '类型', 'required|in_list[1,2]'),
    	);
    	$this->formDataValidation($vConf);
    	$type = post('type');

    	$select = 'm.id,m.title,m.content,m.addtime,m.order_id,v.message_id as viewed';
        $this->db
            ->join($this->mMessage->tbMessageViewed.' v', 'v.message_id = m.id', 'left')
            ->join($this->mMessage->tbMessageDelete.' d', 'd.message_id = m.id', 'left')
            ->where('(m.deliveryman_id = '.$this->userId.' or m.deliveryman_id = 0) and d.message_id is null')
            ->where('m.type', $type)
            ->group_by('m.id')
            ->order_by('m.id desc');

        if($type == 2){//系统推送（订单消息）
            $this->loadModel('DlnOrderModel', 'mOrder');
            $select .= ',o.status,o.income,o.code';
            $this->db
                ->join($this->mOrder->tbOrder.' o', 'o.id = m.order_id');
        }

        $this->db->select($select);

    	$data = $this->mMessage->appPage($this->mMessage->tbMessage.' m', post('page'));

    	$list = [];
    	$viewedData = [];
    	foreach ($data['list'] as $k => $v){

    		$list[$k] = [
    				'id' => $v['id'],
    				'title' => isset($v['title'])?$v['title']:'',
    				'order_id' => isset($v['order_id'])?$v['order_id']:'0',
    				'code' => isset($v['code'])?$v['code']:'',
    				'income' => isset($v['income'])?$v['income']:'0',
    				'content' => isset($v['status'])?'订单'.$this->mOrder->status($v['status']):$v['content'],
    				'addtime' => date('Y-m-d H:i:s', $v['addtime'])
    		];
    		
    		$viewedData[] = [
    							'message_id' => $v['id'],
    							'deliveryman_id' => $this->userId,
    							'addtime' => time()
    		];
    	}
    	
    	$data['list'] = $list;
    	if((bool)$viewedData){
    		$this->mMessage->insertBatch($this->mMessage->tbMessageViewed, $viewedData);
    	}
    	$this->appReturn(1, '', $list);
    }

    /**获取新消息数量*/
    public function getNewMessageCount(){
        $this->loadModel('DlnMessageModel', 'mMessage');
        $count = $this->mMessage->newMessageCount($this->userId);
        $this->appReturn(1, '', $count);
    }

    /**获取系统消息详情*/
    public function getMessageDetail(){
        $this->loadModel('DlnMessageModel', 'mMessage');
        //表单验证
        $vConf = array(
            array('id', '消息id', 'required|numeric'),
        );
        $this->formDataValidation($vConf);
        $this->db->select('id,content,addtime')
                 ->where(array('id' => post('id'),'type' => 1));
        $tA = $this->mMessage->getOne($this->mMessage->tbMessage);
        $tA['addtime'] = dateFormat($tA['addtime'], true);

         $html = $this->view('user/msgDetail', ['info' => $tA],0, 0, 0, true);

        $this->appReturn(1, '', $html);
    }
    
    /**
     * 删除消息
     */
    public function deleteMessage(){
    	
    	$this->loadModel('DlnMessageModel', 'mMessage');
    	//表单验证
    	$vConf = array(
    			array('id', 'id', 'required|numeric'),
    	);
    	$this->formDataValidation($vConf);
    	$id = post('id');
    	$this->db->select('deliveryman_id')
    			->where('id = '.$id.' and (deliveryman_id = '.$this->userId.' or deliveryman_id = 0)');
    	$tA = $this->mMessage->getOne($this->mMessage->tbMessage);
    	if( ! $tA){
    		$this->appReturn(0, '消息不存在或已删除');
    	}
    	
    	if($tA['deliveryman_id'] <= 0){
    		$this->db->where(['message_id' => $id, 'deliveryman_id' => $this->userId]);
    		$tI = $this->mMessage->count($this->mMessage->tbMessageDelete);
    		if($tI){
    			$this->appReturn(0, '消息已删除');
    		}
    		
    		$data = [
    				'message_id' => $id,
    				'deliveryman_id' => $this->userId,
    				'addtime' => time()
    		];
    		
    		$tB = $this->mMessage->insert($this->mMessage->tbMessageDelete, $data);
    		if( ! $tB){
    			$this->appReturn(0, '删除失败');
    		}
    	}else{
    		
    		$this->db->where(['id' => $id, 'deliveryman_id' => $this->userId]);
    		$tB = $this->mMessage->delete($this->mMessage->tbMessage);
    		if( ! $tB){
    			$this->appReturn(0, '删除失败');
    		}
    	}
    	
    	$this->appReturn(1, '已删除');
    }
    
    /**
     * 添加反馈
     */
    public function addFeedback(){
    	
    	$this->loadModel('DlnFeedbackModel', 'mFeedback');
    	//表单验证
    	$vConf = array(
    			array('content', '反馈内容', 'required|max_length[200]|min_length[10]'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$data = [
    				'deliveryman_id' => $this->userId,
    				'content' => trim(post('content')),
    				'reply' => '',
    				'status' => 1,
    				'addtime' => time()
    	];
    	
    	if($this->mFeedback->insert($this->mFeedback->tbFeedback, $data)){
    		$this->appReturn(1, '已提交');
    	}
    	
    	$this->appReturn(1, '保存失败');
    }
    
    /**
     * 获取反馈列表
     */
    public function getFeedbackList(){
    	
    	$this->loadModel('DlnFeedbackModel', 'mFeedback');
    	//表单验证
    	$vConf = array(
    			array('page', '页码', 'required|numeric'),
    	);
    	$this->formDataValidation($vConf);
    	
    	$this->db->select('id,content,reply,status,addtime')
    			 ->where('deliveryman_id', $this->userId)
    			 ->order_by('id desc');
    	$data = $this->mFeedback->appPage($this->mFeedback->tbFeedback, post('page'));
    	foreach ($data['list'] as $k => $v){
    		$data['list'][$k]['addtime'] = date('Y-m-d', $v['addtime']);
    		$data['list'][$k]['status_show'] = $this->mFeedback->status($v['status']);
    	}
    	
    	$this->appReturn(1, '', $data);
    }
    
    /**
     * 验证支付密码
     */
    public function verifyPayPassword(){
        
        //琛ㄥ崟楠岃瘉
        $vConf = array(
            array('password', '支付密码', 'required|exact_length[6]'),
        );
        $this->formDataValidation($vConf);
        $password = post('password');
        $this->_verifyPayPassword($password);
        $this->appReturn(1);
    }

    private function _verifyPayPassword($password){
        $this->db->select('pay_password')
                 ->where('id', $this->userId);
        $info = $this->mUser->getOne($this->mUser->tbUser);
        if($info['pay_password'] != setPassword($password)){
            $this->appReturn(0, '密码错误');
        }
        return true;
    }
}